package com.rongshu.sendmessage.util.event;

import android.util.Log;

import java.util.HashMap;

/**
 * Created by lx on 2017/6/9.
 */
public class EventProvider extends BaseEventProvider {

    private HashMap<String, Class<? extends IEvent>> eventCache = new HashMap<>();
    private final String TAG =EventProvider.class.getSimpleName();
    private static BaseEventProvider eventProvider;

    private EventProvider(){}

    public static synchronized BaseEventProvider init(BaseEventBuilder eventBuilder){
        if(eventProvider == null){
            eventProvider = new EventProvider();
            eventProvider.initEventBuilder(eventBuilder);
        }
        return eventProvider;
    }

    @Override
    public void initEventBuilder(BaseEventBuilder eventBuilder) {
        eventCache.clear();
        HashMap<String, Class<? extends IEvent>> events = eventBuilder.buildEvents();
        Log.i(TAG,"events："+events.size());
        if(events != null){
            Log.i(TAG,"put all events：" + events.size());
            eventCache.putAll(events);
        }
        events.clear();
    }

    @Override
    public IEvent getEvent(Class<?> subscribeCls, String methodName) {
        try{
            String key = subscribeCls.getSimpleName()+"_" +methodName;
            return (IEvent) eventCache.get(key).newInstance();
        }catch(Exception e){
            Log.i(TAG,e.getMessage());
            e.printStackTrace();
        }
        return null;
    }

    @Override
    public HashMap<String, Class<? extends IEvent>> getEvents() {
        return eventCache;
    }

}
